#include <QCoreApplication>
#include <QDBusInterface>
#include <QDBusReply>
#include <QDBusMessage>
#include <QTimer>
#include <QObject>
#include <QDebug>
#include <QDBusVariant>
#include <QDBusReply>

class Worker : public QObject
{
	Q_OBJECT

	public:
		Worker();
		~Worker();

	private:
		void getProperty();

		public slots:
			void statusChanged(QString, QVariantMap, QStringList);

	private:
		QTimer* m_timer;
		QDBusInterface* m_it;
		QString m_service, m_path, m_interface,
				m_name, m_mac;

};

Worker::Worker()
	:QObject(nullptr)
{
	m_timer = new QTimer(this);
	QString mac = "44_E5_17_2A_CC_FD";
	m_mac = "MING";
	m_service ="org.bluez";
	m_path = "/org/bluez/hci0/dev_"+mac;
	m_interface = "org.freedesktop.DBus.Properties";
	m_name = "PropertiesChanged";

	// m_path = "/org/bluez/hci0/dev_44_E5_17_2A_CC_FD";
	m_it = new QDBusInterface(m_service, m_path, m_interface, QDBusConnection::systemBus(), this);

	bool ok = QDBusConnection::systemBus().connect(m_service, m_path, m_interface,m_name, this, SLOT(statusChanged(QString, QVariantMap, QStringList)));
	qDebug() << "connect: " << ok << m_it->lastError().message();

	QDBusReply<QDBusVariant> rpl = m_it->call("Get", "org.bluez.Device1", "Name");
	if(rpl.isValid()){
		auto v= rpl.value().variant();
		qDebug() << "===ok-name:" << v;
	}
	else
		qDebug() << "====fail" << m_it->lastError() << rpl.error().message();

}

Worker::~Worker()
{
}


void Worker::statusChanged(QString name, QVariantMap v1, QStringList v2)
{
	// qDebug() << name;
	if(name == "org.bluez.Device1") {
		qDebug() << v1 << v2;
		bool connected = v1.value("Connected", false).toBool();
		if(connected) {
			// QString startBlueTootchNetwork = "bt-network -c " + m_mac + " panu";
			// system(startBlueTootchNetwork.toStdString().c_str());
			system("bash -c 'sleep 3 ;bt-network -c MING panu'");
		}
	}
}

void Worker::getProperty()
{


}

int main(int c, char** v)
{
	QCoreApplication a(c, v);
	Worker w;

	return a.exec();
}

#include "main.moc"
